package rwt.server.handlers.web;

import org.slf4j.*;

import rwt.server.*;
import rwt.server.RailroadMessages.LocoDirfMsg;
import rwt.server.RailroadMessages.LocoSpdMsg;
import rwt.server.RailroadMessages.WriteSlotDataToClearMsg;
import rwt.server.WebMessages.CloseThrottle;
import rwt.server.WebMessages.PutAvailableTrains;
import rwt.server.core.*;
import rwt.server.mtl.java.MessageTranslationLibrary.*;
import rwt.server.railroad.*;

public class CloseThrottleHandler extends MessageHandler<CloseThrottle>
{
	private static final Logger logger = LoggerFactory.getLogger(CloseThrottleHandler.class);
	
	@Override
	public void handle(CloseThrottle message, IConnection source) throws Exception
	{
		logger.info("Closing throttle " + message.trainId);
		
		Train t = RailServer.getTrainManager().getTrainById(message.trainId);
		int slot = t.getVirtualSlotNum();
		RailroadSystem system = t.isEmergency() ? RailServer.getRailroadServer() : RailServer.getController();
		
		// Stop the train
		LocoSpdMsg speedMsg = new LocoSpdMsg(slot, 0);
		system.write(speedMsg);
		
		// Set direction to forward; turn off bell, horn, and lights
		LocoDirfMsg dirfMsg = new LocoDirfMsg(slot, 
				DirectionType.Forward, 
				OnOffType.Off, 
				OnOffType.Off, 
				OnOffType.Off);
		system.write(dirfMsg);
		
		if (t.isEmergency()) {
			// For emergency throttles, clear the slot entry since throttle is now closed
			WriteSlotDataToClearMsg clearMsg = new WriteSlotDataToClearMsg(slot);
			RailServer.getRailroadServer().write(clearMsg);
		}
		
		t.closeThrottle();
		
		PutAvailableTrains availableTrainsMsg = RailServer.getTrainManager().getPutAvailableTrains();
		RailServer.getClientManager().sendToAll(availableTrainsMsg);
	}
}
